<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  example all rights reserved.
 */
namespace service;

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * 对象存储OSS文件服务 -- 暂只支持七牛云 -- 待集成阿里云SDK等
 * Class OssService.
 */
class OssService
{
    /**
     * 获取OSS文件当前URL地址
     *
     * @param      $filename string 文件名
     * @param null $storage  存储方式
     *
     * @throws \Exception
     * @return bool|string
     */
    public static function getFileUrl($filename, $storage = null)
    {
        $storage_type = config('oss.storage_type_default');

        if (false === self::hasFile($filename, $storage)) {
            return false;
        }

        switch (empty($storage) ? $storage_type : $storage) {
            case 'qiniu':
                return self::getBaseUriQiniu() . $filename;
        }

        return false;
    }

    /**
     * 根据配置获取到七牛云文件上传目标地址
     *
     * @param bool $isClient 是否客户端
     */
    public static function getUploadQiniuUrl($isClient = true)
    {
        $config = config('oss.qiniu');
        $isHttps = (bool) $config['is_https'];

        switch ($config['region']) {
            case '华东':
                if ($isHttps) {
                    return $isClient ? 'https:///upload.qiniup.com' : 'https://upload.qiniup.com';
                }

                return $isClient ? 'http:///upload.qiniup.com' : 'http://upload.qiniup.com';
            case '华北':
                if ($isHttps) {
                    return $isClient ? 'https://upload-z1.qiniup.com' : 'https://up-z1.qiniup.com';
                }

                return $isClient ? 'http://upload-z1.qiniup.com' : 'http://up-z1.qiniup.com';
            case '北美':
                if ($isHttps) {
                    return $isClient ? 'https://upload-na0.qiniup.com' : 'https://up-na0.qiniup.com';
                }

                return $isClient ? 'http://upload-na0.qiniup.com' : 'http://up-na0.qiniup.com';
            case '华南':
            default:
                if ($isHttps) {
                    return $isClient ? 'https://upload-z2.qiniup.com' : 'https://up-z2.qiniup.com';
                }

                return $isClient ? 'http://upload-z2.qiniup.com' : 'http://up-z2.qiniup.com';
        }
    }

    /**
     * 获取七牛云URL前缀
     */
    public static function getBaseUriQiniu()
    {
        $config = config('oss.qiniu');

        switch ($config['is_https']) {
            case 'https':
                return 'https://' . $config['domain'] . '/';
            case 'http':
                return 'http://' . $config['domain'] . '/';
            default:
                return '//' . $config['domain'] . '/';
        }
    }

    /**
     * 检查OSS上文件是否已经存在.
     *
     * @param      $filename
     * @param null $storage
     *
     * @throws \think\exception\PDOException
     * @throws \think\Exception
     * @return bool
     */
    public static function hasFile($filename, $storage = null)
    {
        $storage_type = config('oss.storage_type_default');

        switch (empty($storage) ? $storage_type : $storage) {
            case 'qiniu':
                $config = config('oss.qiniu');
                /** @var Auth $auth */
                $auth = app(
                    Auth::class,
                    ['accessKey' => $config['access_key'], 'secretKey' => $config['secret_key']]
                );
                /** @var BucketManager $bucketMgr */
                $bucketMgr = app(BucketManager::class, ['auth' => $auth]);
                list($ret, $err) = $bucketMgr->stat($config['bucket'], $filename);

                return null === $err;
        }

        return false;
    }

    /**
     * 根据OSS的文件Key读取文件内容.
     *
     * @param string $filename 文件名称
     * @param string $storage  存储方式
     *
     * @throws \Exception
     * @return null|bool|string
     */
    public static function readFile($filename, $storage = '')
    {
        $storage_type = config('oss.storage_type_default');

        switch (empty($storage) ? $storage_type : $storage) {
            case 'qiniu':
                $config = config('oss.qiniu');
                /** @var Auth $auth */
                $auth = app(
                    Auth::class,
                    ['accessKey' => $config['access_key'], 'secretKey' => $config['secret_key']]
                );

                return file_get_contents($auth->privateDownloadUrl(self::getBaseUriQiniu() . $filename));
        }

        return null;
    }

    /**
     * 七牛云存储.
     *
     * @param string $filename 文件名
     * @param string $content  上传内容(文件路径)
     * @param bool   $isPath   是否路径
     *
     * @throws \Exception
     */
    public static function qiniu($filename, $content, $isPath = false)
    {
        $config = config('oss.qiniu');
        /** @var Auth $auth */
        $auth = app(
            Auth::class,
            ['accessKey' => $config['access_key'], 'secretKey' => $config['secret_key']]
        );
        $token = $auth->uploadToken($config['bucket']);
        $uploadMgr = new UploadManager();

        if ($isPath) {
            list($result, $err) = $uploadMgr->putFile($token, $filename, $content);
        } else {
            list($result, $err) = $uploadMgr->put($token, $filename, $content);
        }

        if (null !== $err) {
            return false;
        }

        $result['file'] = $filename;
        $result['url'] = self::getBaseUriQiniu() . $filename;

        return $result;
    }
}
